import type { RouteRecordRaw } from "vue-router";

//一个被匹配到的菜单
export let firstMenu: any = null

/**
 * 
 * 添加动态路由函数的处理
 */
export function mapMenusToRoutes(userMenus: any[]) {
  //添加动态路由
  const localRoutes: RouteRecordRaw[] = []
  //读取router/main下面的所有TS文件
  const files: Record<string, any> = import.meta.glob('../router/main/**/*.ts', {
    eager: true
  })
  // console.log(files)

  //将加载对象放到localRoutes
  for(const key in files) {
    const module = files[key]
    // console.log(module.default)
    localRoutes.push(module.default)
  }
  
  const routes: RouteRecordRaw[] = [] 

  //根据菜单去匹配正确的路径
  for(const menu of userMenus) {
    for(const submenu of menu.children) {
      const route = localRoutes.find(item => item.path === submenu.url) 
      // if(route) router.addRoute('main', route)
      if(route) {
         // 1.给route的顶层菜单增加重定向功能(但是只需要添加一次即可)
         if (!routes.find((item) => item.path === menu.url)) {
            routes.push({ path: menu.url, redirect: route.path })
          }
        // 2.将二级菜单对应的路径
        routes.push(route)
      }
      //记录第一个被匹配到的菜单
      if(!firstMenu && route) firstMenu = submenu
    }
  }

  return routes
}

/**
 * 
 * 根据路径匹配需要显示的菜单
 */
export function mapPathMenu(path: string, userMenus: any[]) {
  for(const menu of userMenus) {
    for(const submenu of menu.children) {
      if(submenu.url === path) {
        return submenu
      }
    }
  }
}



interface IBreadcrumbs {
  name: string
  path: string
}
export function mapPathToBreadCrumbs(path: string, userMenus: any[]) {
  // 1.定义面包屑
  const breadcrumbs: IBreadcrumbs[] = []

  // 2.遍历获取面包屑层级
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        // 1.顶层菜单
        breadcrumbs.push({ name: menu.name, path: menu.url })
        // 2.匹配菜单
        breadcrumbs.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrumbs
}